<?php
class DbSession extends Session {
    protected static $sessTable = null;
    protected $founded = false;
    protected function __construct() {
        self::$sessTable = Table::getTable('SESSION', Config::get('SESSION_DBCONN'));
    }
    
    public function open() {}
    public function close() {}

    public function read() {
        $sessData = self::$sessTable->find(array('sess_id'=>session_id()));
        if ($sessData) {
            $this->founded = true;
            $_SESSION = unserialize($sessData['sess_data']);
        }
        return $_SESSION;
    }
    
    public function write() {
        if ($_SESSION) {
            $sessData = array('sess_id'=>session_id(),
                          'sess_data'=>serialize($_SESSION),
                          'updated'=>time());
            if ($this->founded) {
                self::$sessTable->save($sessData, array('sess_id'=>session_id()));
            } else {
                self::$sessTable->save($sessData);
            }
        } else {
            $this->sessDestroy();
        }
    }
    
    public function sessDestroy() {
        $_SESSION = array();
        self::$sessTable->delete(array('sess_id'=>session_id()));
        $this->founded = false;
    }
    
    public function gc() {
        $gcMaxLife = Config::get('SESSION_LIFETIME');
        $gcMaxLife = $gcMaxLife >= 86400 ? $gcMaxLife : 86400;
        self::$sessTable->delete('updated < ' . (time() - $gcMaxLife));
        self::$sessTable->vacuum();
    }
    
    public static function delete($sessionId) {
        
    }
};
?>